#include "GlassMaterial.h"

using namespace OBR;

std::shared_ptr<CudaProgram> GlassMaterial::program;
CudaBuffer GlassMaterial::sbt_data_payload;

GlassMaterial::GlassMaterial() : Material("shaders/Material/GlassMaterial.cu"), eta(1.5f)
{
    this->program_desc.callables.entryFunctionNameDC = "__direct_callable__glass_material";
    this->program_desc.kind = OPTIX_PROGRAM_GROUP_KIND_CALLABLES;
    this->program_desc.flags = OPTIX_GEOMETRY_FLAG_NONE;
}

GlassMaterial::~GlassMaterial()
{
}

void GlassMaterial::uploadVirtualProgramPayload(
    std::vector<std::shared_ptr<VirtualProgramEntry>> instances)
{
    // collect data
    GlassMaterialData *data = new GlassMaterialData[instances.size()];
    for (size_t i = 0; i < instances.size(); i++)
    {
        auto mat = std::dynamic_pointer_cast<GlassMaterial>(instances[i]);
        data[i].eta = mat->eta;
    }

    // set payload
    size_t payload_size = sizeof(GlassMaterialData) * instances.size();
    this->sbt_data_payload.resize(payload_size);
    this->sbt_data_payload.upload(data, payload_size);

    delete[] data;
}

void GlassMaterial::_buildFromConfig(const Json::Value &config)
{
    if (config["type"].asString().compare("glass") != 0)
    {
        std::cerr << "wrong config value is sent to GlassMaterial::_buildFromConfig" << std::endl;
        std::cerr << "got:" << config << std::endl;
        throw std::runtime_error("invalid parameter");
    }
    this->eta = config["eta"].asFloat();
}

CUdeviceptr GlassMaterial::getPayloadDevicePtr()
{
    return GlassMaterial::sbt_data_payload.d_pointer();
}

void GlassMaterial::setProgram(std::shared_ptr<CudaProgram> prog)
{
    GlassMaterial::program = prog;
}

std::shared_ptr<CudaProgram> GlassMaterial::getProgram()
{
    return GlassMaterial::program;
}

OptixProgramGroupOptions &GlassMaterial::getProgramGroupOptions()
{
    return this->program_opt;
}

OptixProgramGroupDesc &GlassMaterial::getProgramGroupDesc()
{
    this->program_desc.callables.moduleDC = this->cuda_module->optix_module;
    return this->program_desc;
}